//app.js
App({
  onLaunch: function () {

    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        env: 'test-2oth4',
        traceUser: true,
      })
    }


    // const api = require('./libs/api');
    // api.callfun("demo").then(res => {
    //   wx.setStorageSync("appid", res.result.appid);
    //   wx.setStorageSync('openid', res.result.openid);
    // })
    //检验打开小程序的用户是否曾经授权过
    // wx.getSetting({
    //   success: (res) => {
    //     //判断，已授权，就可以直接使用用户信息，
    //     if (res.authSetting["scope.userInfo"]) {
    //       wx.getUserInfo({
    //         success: (data) => {
    //           //判断用户信息是否改变过
    //           let userInfo = wx.getStorageSync('userInfo');
    //           if (userInfo.nickName != data.userInfo.nickName || userInfo.avatarUrl != data.userInfo.avatarUrl) {
    //             wx.setStorageSync('userinfo', data.userInfo);
    //           }
    //         }
    //       })
    //     }
    //   }
    // })


  },

  //全局变量
  globalData: {
    userInfo:{},
    openId: ''
  },
  //toast
  msg: function (text, type) {
    var type = typeof type === "undefined" ? '' : type
    var icon = 'none'
    if (type != '') {
      icon = type
    }
    wx.showToast({
      title: text,
      icon: icon,
      duration: 2000
    })
  },

  exitSaveData:function(){
    //清除缓存
    wx.clearStorageSync()
  },
  //获取登录状态
  getLoginStatus:function(){
    let session = wx.getStorageSync('openid')
    return session == '' ? false : session
  },


  //获取请求domain
  getDomain: function () {
    if (this.globalData.isDebug) {
      return this.globalData.isTest ? 'https://www.yunxiaozhi.cn/test/public/api/' : 'http://danbaixi.utools.club/yxz_v1/public/index.php/api/'
    }
    return 'https://www.yunxiaozhi.cn/v1/public/api/'
  },
  //封装request 
  httpRequest: function (datas) {
    datas.data = datas.data == undefined ? {} : datas.data
    datas.redirect = datas.redirect || ''
    if (datas.needLogin == undefined || datas.needLogin == true) {
      let session = this.getLoginStatus()
      if (session == "") {
        this.msg('请先登录')
        return
      }
      datas.data.session = session
    }
    var that = this,
      isDebug = this.globalData.isDebug,
      domain = this.getDomain(),
      contentType = 'application/json'

    if (typeof datas.method == undefined) {
      datas.method = "GET"
    }
    if (datas.method == "POST") {
      contentType = 'application/x-www-form-urlencoded'
    }
    wx.request({
      url: domain + datas.url + (isDebug ? this.globalData.xdebug : ""),
      data: typeof datas.data == undefined ? '' : datas.data,
      method: datas.method,
      header: {
        'content-type': contentType
      },
      success: function (res) {
        switch (res.data.status) {
          default:
            datas.success(res); break;
          case 4001:
            that.msg('请先登录'); break;
          case 4002:
            that.msg('请先绑定账号'); break;
          case 4003:
            //登陆已过期
            that.msg(res.data.message)
            that.exitSaveData()
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/login/login?redirect=' + datas.redirect,
              })
            }, 1000)
            break;
          case 4004:
            that.msg('您已修改了教务系统密码，请重新绑定账号');
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/bind/bind?rebind=true',
              })
            }, 1000);
            break;
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '请求超时',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

})
